package com.spdg.ring.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Gallery;

public class ScrollOnePageGallery extends Gallery {

	private final static int MOTION_EVENT_X_MAX = 10;
	private final static int MOTION_EVENT_Y_MAX = 10;

	private final static int ORIENTATION_HORIZONTAL = 0;
	private final static int ORIENTATION_VERCATICAL = 1;

	private float start_x;
	private float start_y;

	private boolean locked = false; // 锁住手势
	private boolean intercept = false; // 是否拦截，true：拦截，false：传给子控件 默认：false

	public ScrollOnePageGallery(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		if (locked && !intercept) { // 当上下滚动时，锁住gallery效果
			return true;
		}

		int kEvent;
		if (isScrollingLeft(e1, e2)) {
			// Check if scrolling left
			kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
		} else {
			// Otherwise scrolling right
			kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
		}

		onKeyDown(kEvent, null);
		return true;
	}

	private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
		if (e1 == null || e2 == null)
			return false;
		return e2.getX() > e1.getX();
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		int action = ev.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			locked = false; // 每一次出发滑动，接触锁定趋势
			start_x = ev.getX();
			start_y = ev.getY();
			break;
		case MotionEvent.ACTION_MOVE:

			if (locked) { // 手势锁定后，不再进行手势判定
				ev.setAction(MotionEvent.ACTION_MOVE);
				break;
			}
			final float end_x = ev.getX();
			final float end_y = ev.getY();
			int orient = orientation(start_x, start_y, end_x, end_y);
			switch (orient) {
			case ORIENTATION_HORIZONTAL: // 左右滑动
				intercept = true;
				break;
			case ORIENTATION_VERCATICAL: // 上下滑动
				intercept = false;
				break;
			}
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		return intercept;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		if (locked && !intercept) {
			return true;
		}
		return super.onScroll(e1, e2, distanceX, distanceY);
	}

	// 默认竖向
	private int orientation(float start_x, float start_y, float end_x, float end_y) {

		final int deltal_x = Math.abs((int) (end_x - start_x));
		final int deltal_y = Math.abs((int) (end_y - start_y));

		// System.out.println("===========end_x:" + end_x + " start_x:" +
		// start_x);
		if (deltal_x > MOTION_EVENT_X_MAX || deltal_y > MOTION_EVENT_Y_MAX) {

			// 当判定出滑动趋势，锁死一次的滑动趋势
			locked = true;
			if (deltal_x > deltal_y) { // 横向移动
				return ORIENTATION_HORIZONTAL;
			}
		}
		return ORIENTATION_VERCATICAL;
	}

}
